package com.jiangjun.fetch.filter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiangjun.fetch.FetchRss;
import com.jiangjun.fetch.common.ImageFetch;
import com.jiangjun.fetch.common.WebContext;
import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.jiangjun.fetch.servlet.Start;
import com.jiangjun.fetch.util.PathUtil;
import com.mongodb.DBObject;

/**
 * 保存文本内容
 * 
 * @author Administrator
 * 
 */
public class SaveFileFilter extends Filter {
	private final Logger logger = LoggerFactory.getLogger(SaveFileFilter.class);
	private MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();

	@Override
	public String doProcess(WebContext ctx) throws Exception {
		if (null != ctx.getContent()) {
			String path = PathUtil.getPath(ctx) + ctx.getId();
			writeXmlFile(ctx, path);
			/**
			 * 保存到mongoDB
			 */
			FetchRss fetchTxt = ctx.getFetch();
			fetchTxt.setTxt_path(path);
			if (ctx.getMin_img_db_path() != null
					&& !"".equals(ctx.getMin_img_db_path())) {
				fetchTxt.setMin_img_path(ctx.getMin_img_db_path());
			}
			DBObject object = fetchTxt.toDbObject();
			mongoDBSupport.save(object, MongoDBSupport._FETCHTXT);
		} else {
			// 抓取正文失败
			throw new Exception();
		}
		return null;
	}

	public void writeXmlFile(WebContext ctx, String path) throws Exception {
		String content = output(ctx);
		File file = new File(path);
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			osw = new OutputStreamWriter(os);
			bw = new BufferedWriter(osw);
			bw.write(content);
			bw.flush();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally{
			bw.close();
			osw.close();
			os.close();
		}

		// Document doc = DocumentHelper.createDocument();
		// doc.setText(content);
		// Element root = doc.addElement("root");
		// root.addElement("id").addText(String.valueOf(ctx.getId()));
		// root.addElement("title");
		// root.addElement("time");
		// root.addElement("from");
		// root.addElement("description");
		// root.addElement("content").addText("<![CDATA[" + output(ctx) +
		// "]]>");
		// root.addElement("images");
		//
		// XMLWriter writer = null;
		// try {
		// OutputFormat format = OutputFormat.createPrettyPrint();
		// // format.setEncoding("utf-8");// 设置XML文件的编码格式
		// // format.setSuppressDeclaration(true); // 去除<?xml version="1.0"
		// // encoding="UTF-8"?>
		// writer = new XMLWriter(new FileWriter(new File(path)), format);
		// writer.setEscapeText(false); // 反转义
		// writer.write(doc);
		// writer.flush();
		// } catch (Exception e) {
		// // TODO: handle exception
		// throw new Exception();
		// } finally {
		// if (writer != null) {
		// writer.close();
		// }
		// }

	}

	private String output(WebContext ctx) {
		Element element = null;
		try {
			 Element ele = (Element) ctx.getContent();
			 Document docment = DocumentHelper.createDocument();
			 Element comxhtml = docment.addElement("HTML");
			 comxhtml.addElement("HEAD").addElement("TITLE");
			 comxhtml.add(ele.detach());
			 element = docment.getRootElement();
			List<ImageFetch> imgList = ctx.getImgList();
			for (ImageFetch is : imgList) {
				Element imgEle = (Element) element
						.selectSingleNode("//*[@id=\"" + is.getImg_id() + "\"]");
				// 如果需要被删除，则删除该图片标签
				if (null != imgEle) {
					if (is.isNeedRemove()) {
						imgEle.detach();
						continue;
					} else {
						if (is.getImg_path() != null
								&& !"".equals(is.getImg_path())) {
							int w = (int) (is.getWidth() * Double
									.parseDouble(is.getScale_min()));
							int h = (int) (is.getHeight() * Double
									.parseDouble(is.getScale_min()));
							imgEle.addAttribute("src", Start.imgServer
									+ "?src=" + is.getImg_path());
							imgEle.addAttribute("width", "" + w);
							imgEle.addAttribute("height", "" + h);
						} else {
							imgEle.detach();
						}
					}
				}
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String resString = element.selectSingleNode("/HTML/BODY").asXML();
		resString = resString.replaceAll("<BODY>", "");
		resString = resString.replaceAll("</BODY>", "");
		resString = resString.replaceAll("<UL", "<DIV");
		resString = resString.replaceAll("</UL>", "</DIV>");
		ctx.setContent(resString);
		return resString;
	}
}
